//
//  ChatFriendViewController.m
//  MarryMe
//
//  Created by lanou3g on 16/1/13.
//  Copyright © 2016年 revocher. All rights reserved.
//

#import "ChatFriendViewController.h"
#import <AVOSCloud.h>
#import "FriendTableViewCell.h"
#import "UIImageView+WebCache.h"
#import "ChatViewController.h"
#import "RootViewController.h"
@interface ChatFriendViewController ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate>
@property (strong, nonatomic) IBOutlet UITableView *frendTableView;
@property(strong,nonatomic)AVObject *friendObj;
@property(strong,nonatomic) NSMutableArray * friendArr;
@property(strong,nonatomic) NSString *nameStr;

@end

@implementation ChatFriendViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.frendTableView.delegate = self;
    self.frendTableView.dataSource = self;
    AVQuery *query1 = [AVQuery queryWithClassName:[NSString stringWithFormat:@"Friend%@",[AVUser currentUser].username]];
    self.friendObj = [query1 getFirstObject];
    if (self.friendObj==nil) {
        self.friendObj = [AVObject objectWithClassName:[NSString stringWithFormat:@"Friend%@",[AVUser currentUser].username]];
    }
    self.friendArr  = [NSMutableArray array];
    if ([self.friendObj objectForKey:[NSString stringWithFormat:@"Friend%@",[AVUser currentUser].username]]!=nil) {
        self.friendArr  =[self.friendObj objectForKey:[NSString stringWithFormat:@"Friend%@",[AVUser currentUser].username]];
    }
    UIBarButtonItem *leftIrem = [[UIBarButtonItem alloc]initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(leftItemAction:)];
    self.navigationItem.leftBarButtonItem = leftIrem;    UIBarButtonItem *rightitem = [[UIBarButtonItem alloc]initWithTitle:@"添加好友" style:UIBarButtonItemStylePlain  target:self  action:@selector(rightItemAction:)];
    self.navigationItem.rightBarButtonItem = rightitem;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)leftItemAction:(UIBarButtonItem *)sender{
    RootViewController *affVC = [[RootViewController alloc]init];
    affVC.selectedIndex = 2;
    [self.navigationController presentViewController:affVC animated: YES completion:nil];
    
}




- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString  *cell_id = @"FriendTableViewCell";
     FriendTableViewCell  *cell = [tableView dequeueReusableCellWithIdentifier:cell_id];
    if (!cell) {
        //加载可视化文件
        cell = [[NSBundle mainBundle]loadNibNamed:@"FriendTableViewCell" owner:self options:nil].firstObject ;
    }
    AVQuery *query = [AVQuery queryWithClassName:@"_File"];
    cell.photoView.image =[UIImage imageNamed:@"tutu.jpg"];
    cell.photoView.layer.cornerRadius = 30;
    cell.photoView.clipsToBounds =YES;
    
    [query whereKey:@"name" equalTo:[NSString stringWithFormat:@"%@.png",self.friendArr[indexPath.row]]];
    [query getFirstObjectInBackgroundWithBlock:^(AVObject *object, NSError *error) {
        if (object != nil) {
            NSString *strUrl = [object objectForKey:@"url"];
         [cell.photoView sd_setImageWithURL:[NSURL URLWithString:strUrl]];
        
        }
    }];
        


    cell.nameLabel.text = self.friendArr[indexPath.row];
    return cell;
    
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.friendArr.count;
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 70;

}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    ChatViewController *chat = [[ChatViewController alloc]init];
    //新建一个聊天会话View Controller对象
    //设置会话的类型，如单聊、讨论组、群聊、聊天室、客服、公众服务会话等
    chat.targetId = self.friendArr[indexPath.row];
    chat.conversationType = ConversationType_PRIVATE;
    
    //设置聊天会话界面要显示的标题
    chat.title =self.friendArr[indexPath.row];
    //显示聊天会话界面
    UINavigationController * chatNC = [[UINavigationController alloc]initWithRootViewController:chat];
    chat.key = 1;
    chat.name =self.friendArr[indexPath.row];
    [self.navigationController presentViewController:chatNC animated:YES completion:nil];


}
-(void)rightItemAction:(UIBarButtonItem*)sender{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提醒" message:@"请输入想添加好友的昵称" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField){
        textField.placeholder = @"请输入对方的昵称";
        //设置会话的目标会话ID。（单聊、客服、公众服务会话为对方的ID，讨论组、群聊、聊天室为会话的ID）
        textField.delegate = self;
        
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //判断是否已经是好友
        AVQuery *query1 = [AVQuery queryWithClassName:[NSString stringWithFormat:@"Friend%@",self.nameStr]];
        AVObject *obj1 = [query1 getFirstObject];
        if (obj1==nil) {
            obj1 = [AVObject objectWithClassName:[NSString stringWithFormat:@"Friend%@",self.nameStr]];
        }
        
        NSMutableArray *arr1 = [NSMutableArray array];
        if ([obj1 objectForKey:[NSString stringWithFormat:@"Friend%@",self.nameStr]]!=nil) {
            arr1 = [obj1 objectForKey:[NSString stringWithFormat:@"Friend%@",self.nameStr]];
        }
        int i = 0;
        for (NSString  *key in arr1) {
            if ([key isEqualToString:[AVUser currentUser].username]) {
                i++;
            }
        }
        if (i>0) {
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提醒" message:@"你们已经是好友了请不要重复添加~" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
            [alertController addAction:cancelAction];
            [self.navigationController presentViewController:alertController animated:YES completion:nil];
            
        }else{
            AVQuery *query = [AVQuery queryWithClassName:[NSString stringWithFormat:@"Post%@",self.nameStr]];
            AVObject *obj = [query getFirstObject];
            if (obj==nil) {
                obj = [AVObject objectWithClassName:[NSString stringWithFormat:@"Post%@",self.nameStr]];
            }
            
            NSMutableArray *arr = [NSMutableArray array];
            if ([obj objectForKey:[NSString stringWithFormat:@"Post%@",self.nameStr]]!=nil) {
                arr = [obj objectForKey:[NSString stringWithFormat:@"Post%@",self.nameStr]];
            }
            NSLog(@"%@________________",obj);
            int j=0;
            for (NSString *str in arr) {
                if ([str isEqualToString:[AVUser currentUser].username]) {
                    j++;
                }
            }
            if (j>0) {
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提醒" message:@"您已经发送过请求了请不要重复发送~" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
                [alertController addAction:cancelAction];
                [self.navigationController presentViewController:alertController animated:YES completion:nil];
            }else{
                [arr addObject:[AVUser currentUser].username];
                [obj setObject: arr forKey:[NSString stringWithFormat:@"Post%@",self.nameStr]];
                [obj saveInBackground];
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"恭喜" message:@"好友请求发送成功~" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
                [alertController addAction:cancelAction];
                 [self.navigationController presentViewController:alertController animated:YES completion:nil]; 
            }
        }
  //    AVQuery *query = [AVQuery queryWithClassName:[NSString stringWithFormat:@"Post%@",self.nameStr]];
//    AVObject *obj = [query getFirstObject];
//        if (obj==nil) {
//     obj = [AVObject objectWithClassName:[NSString stringWithFormat:@"Post%@",self.nameStr]];
//        }
//
//          NSMutableArray *arr = [NSMutableArray array];
//        if ([obj objectForKey:self.nameStr]!=nil) {
//            arr = [obj objectForKey:self.nameStr];
//        }
//        [arr addObject:[AVUser currentUser].username];
//        [obj setObject: arr forKey:[NSString stringWithFormat:@"Post%@",self.nameStr]];
//        [obj saveInBackground];
//
       }];
    [alertController addAction:cancelAction];
    [alertController addAction:okAction];
    
    [self presentViewController:alertController animated:YES completion:nil];
    
  }
-(void)textFieldDidEndEditing:(UITextField *)textField{
    self.nameStr = textField.text;
    
}





@end
